package me.zhengjie.modules.xiao.rest;

import cn.hutool.core.date.DateUtil;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.vo.UserQueryCriteria;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.xiao.domain.CgSalespersontable;
import me.zhengjie.modules.xiao.service.CgSalespersontableService;
import me.zhengjie.modules.xiao.domain.vo.CgSalespersontableQueryCriteria;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

import static cn.hutool.core.date.DatePattern.NORM_DATE_PATTERN;

/**
* @author cg
* @date 2024-06-19
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "业务员管理")
@RequestMapping("/api/cgSalespersontable")
public class CgSalespersontableController {

    private final CgSalespersontableService cgSalespersontableService;
    private final UserService userService;
    private final DeptService deptService;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('cgSalespersontable:list')")
    public void exportCgSalespersontable(HttpServletResponse response, CgSalespersontableQueryCriteria criteria) throws IOException {
        JwtUserDto userDetails = (JwtUserDto)SecurityUtils.getCurrentUser();
        List<Long> jobs = userDetails.getUser().getJobs().stream().map(Job::getId).collect(Collectors.toList());
        Long deptId = userDetails.getUser().getDept().getId();
        Integer level = userDetails.getLevel();
        if(jobs.contains(8L)){
            if (level == 3||level == 4) {
                UserQueryCriteria userCriteria = new UserQueryCriteria();
                List<Dept> data = deptService.findByPid(deptId);
                // 然后把子节点的ID都加入到集合中
                userDetails.getDataScopes().get(0);
                List<Long> deptIds = deptService.getDeptChildren(data);
                deptIds.add(deptId);
                deptIds.retainAll(userDetails.getDataScopes());
                userCriteria.getDeptIds().addAll(deptIds);
                if(level == 3){
                   deptIds.add(0L);
                }
                criteria.getDeptIds().addAll(deptIds);
                criteria.getCreateBys().add(userDetails.getUser().getUsername());
            }
        }else{
            criteria.getCreateBys().add(userDetails.getUser().getUsername());
        }
        if(StringUtils.isNotBlank(criteria.getTime())){
            List<Date> createTimeList = new ArrayList<>();
            Date date = DateUtil.parse(criteria.getTime(),NORM_DATE_PATTERN);
            createTimeList.add( DateUtil.beginOfDay(date));
            createTimeList.add( DateUtil.endOfDay(date));
            criteria.setCreateTimeList(createTimeList);
        }
        cgSalespersontableService.download(cgSalespersontableService.queryAll(criteria), response);
    }

    @GetMapping(value = "/page")
    @Log("查询业务员")
    @ApiOperation("查询业务员")
    @PreAuthorize("@el.check('cgSalespersontable:list')")
    public ResponseEntity<PageResult<CgSalespersontable>> queryCgSalespersontable(CgSalespersontableQueryCriteria criteria, Page<Object> page){
        JwtUserDto userDetails = (JwtUserDto)SecurityUtils.getCurrentUser();
        List<Long> jobs = userDetails.getUser().getJobs().stream().map(Job::getId).collect(Collectors.toList());
        Long deptId = userDetails.getUser().getDept().getId();
        Integer level = userDetails.getLevel();
        if(jobs.contains(8L)){
            if (level == 3||level == 4) {
                UserQueryCriteria userCriteria = new UserQueryCriteria();
                List<Dept> data = deptService.findByPid(deptId);
                // 然后把子节点的ID都加入到集合中
                userDetails.getDataScopes().get(0);
                List<Long> deptIds = deptService.getDeptChildren(data);
                deptIds.add(deptId);
                deptIds.retainAll(userDetails.getDataScopes());
                userCriteria.getDeptIds().addAll(deptIds);
                if(level == 3){
                   deptIds.add(0L);
                }
                criteria.getDeptIds().addAll(deptIds);
                criteria.getCreateBys().add(userDetails.getUser().getUsername());
            }
        }else{
            criteria.getCreateBys().add(userDetails.getUser().getUsername());
        }
        if(StringUtils.isNotBlank(criteria.getTime())){
            List<Date> createTimeList = new ArrayList<>();
            Date date = DateUtil.parse(criteria.getTime(),NORM_DATE_PATTERN);
            createTimeList.add( DateUtil.beginOfDay(date));
            createTimeList.add( DateUtil.endOfDay(date));
            criteria.setCreateTimeList(createTimeList);
        }
        return new ResponseEntity<>(cgSalespersontableService.queryAll(criteria,page),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增业务员")
    @ApiOperation("新增业务员")
    @PreAuthorize("@el.check('cgSalespersontable:add')")
    public ResponseEntity<Object> createCgSalespersontable(@Validated @RequestBody CgSalespersontable resources){
        String userName = SecurityUtils.getCurrentUsername();
        resources.setCreateBy(userName);
        resources.setCreateTime(DateUtil.date().toTimestamp());
        cgSalespersontableService.create(resources);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PutMapping
    @Log("修改业务员")
    @ApiOperation("修改业务员")
    @PreAuthorize("@el.check('cgSalespersontable:edit')")
    public ResponseEntity<Object> updateCgSalespersontable(@Validated @RequestBody CgSalespersontable resources){
        String userName = SecurityUtils.getCurrentUsername();
        resources.setUpdateBy(userName);
        resources.setUpdateTime(DateUtil.date().toTimestamp());
        cgSalespersontableService.update(resources);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping
    @Log("删除业务员")
    @ApiOperation("删除业务员")
    @PreAuthorize("@el.check('cgSalespersontable:del')")
    public ResponseEntity<Object> deleteCgSalespersontable(@RequestBody List<Integer> ids) {
        cgSalespersontableService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}